<?
/**
 * Engine One Sitemap Generator
 * Please read the LICENSE file
 *
 * @copyright oneDot only <we@onedotonly.be>
 * @author Koen Betsens <koen@onedotonly.be>
 * @package Engine
 * @license GNU Lesser General Public License
 */

require_once("engine/www/combustion.php");

// check if file already exists in db
if( $id = (int) $DB->get_key( "rss", "meta like '%hook%sitemap%'", "ID" )) {

	$file = new OBJECT( "rss", $id );

} else {

	$file	= new OBJECT( "rss", 0, true );
	$textid	= $Engine->text->set( "sitemap", 0, "short", engine_get( 'lang.master' ));
	
	$file->set( "meta", json_encode( array( "hook" => "sitemap" )));
	$file->set( "nameid", $textid );

	$stick = true;
	
}

// create or get file name
$file_name = ROOT . ACCOUNT . "/www/DB/files/sitemap.{$file->id}.xml";

// basic url
$url = engine_get('url');

if( $stick || $DB->get_key( "page", "flog > '{$file->get( 'llog' )}'", "ID" )) {

	$fw = @fopen( $file_name, 'w') or die("can't open file");

	// query for pages
	$pages = $DB->filter_key("page", "active = 1 AND private = 0 ORDER BY hierarchy ASC", array("ID", "name", "parent", "nameid"));
	
	// xmlm header
	$xml_output = "<?xml version='1.0' encoding='UTF-8'?>\n";
	$xml_output .= "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"\n";
	$xml_output .= "\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
	$xml_output .= "\txsi:schemaLocation=\"http://www.sitemaps.org/schemas/sitemap/0.9 ";
	$xml_output .= "\t\thttp://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd\">\n";
	
	// first item (homepage)
	$xml_output .= "\t<url>\n";
	$xml_output .= "\t\t<loc>" . $url . "</loc>\n";
	$xml_output .= "\t\t<changefreq>daily</changefreq>\n";
	$xml_output .= "\t\t<priority>1</priority>\n";
	$xml_output .= "\t</url>\n";
	
	foreach ($pages as $page) {
	
		//print_r($page);
		// get link
		$pageId		= new PAGE( (int) $page['ID'] );
		$page_url	= htmlspecialchars($pageId->url());
		
		// make level
		$level		= 0;
		$parent		= $page['parent'];
	
		// loop through parents
		while ($level < $parent) {
			$level++;
			$parent = $DB->get_key("page", "active = 1 AND private = 0 AND ID = '" . $parent . "'", "parent" );	
		}
		
		// set priority
		if ($level <= 3) $priority 	= 0.8 - ($level * 0.2); 
		else $priority = 0.2;
		
		$xml_output .= "\t<url>\n";
		$xml_output .= "\t\t<loc>" . $page_url . "</loc>\n";
		$xml_output .= "\t\t<changefreq>daily</changefreq>\n";
		$xml_output .= "\t\t<priority>" . $priority . "</priority>\n";
		$xml_output .= "\t</url>\n";
	
	}
		
	$xml_output .= "</urlset>";
		
	$file->set( "llog", date( "Y-m-d H:i:s" ));
		
	fwrite( $fw, $xml_output );
	fclose( $fw );


// read old file if there weren't any updates
} else {

	$fh = fopen( $file_name, 'r' ) or die( "can't open file" );
	$xml_output = fread( $fh, filesize( $file_name ));

}


// output
header("Content-type: text/xml");
print $xml_output;


/*
class SITEMAP {

	// constructor 
	public function __construct($page_list) {
		
		// Instantiate the class with a list of all pages.
		$this->all_pages = $page_list;
		$this->levels = 1;
		
		// Generate the sitemap from the top-level pages (parent=0)
		$this->sitemap = $this->make_sitemap($this->get_items("parent", 0, true));
	}
	
	// Loops through parents and parents of parents until an ancestor with no parents is found.
	// Prepends names of parents to a string and returns the path.		
	// Example: services/methodology
	private function generate_path($id) {
		$level = 0;
		$item = $this->get_items("id", $id);
		$status = $item['status'];
		while ($item['parent'] > 0) {
			$string = $item['name'] . "/" . $string;
			$item = $this->get_items("id", $item['parent']);
			$level += 1;
			// Raise the levels counter if this is a higher level, and status = 1
			if ($level + 1 > $this->levels && $status == 1) {
				$this->levels = $level + 1;
			}
		}
		# Remember to prepend the top-level.
		$string = $item['name'] . "/" . $string;
		return Array(
				"url" => $string, 
				"level" => $level,
				"status" => $status,
		);
	}

	// Returns an item with [$key] of $value.
	// If $multi is true it returns an Array of items where those constraints apply.
	private function get_items($key, $value, $multi=False) {
		foreach($this->all_pages as $page) {
			if ($page[$key] == $value) {
				if ($multi) {
					$items[] = $page;
				}
				else {
					return $page; 
				}
			}
		}
		if ($multi) {
			return $items;
		}
		else {
			return False;
		}
	}

	// Expects a list of pages in an array.
	// Returns an array of links, ordered by level and hierarchy.
	// $flat defaults to true, if false the array reflects the structure of the menu.
	private function make_sitemap($item_list, $flat=true) {
		foreach ($item_list as $item) {
			$links[] = $this->generate_path($item['id']);
			$children = $this->get_items("parent", $item['id'], true);
			if ($children) {
				if ($flat) {
					# Flatten the Array.
					$new_links = $this->make_sitemap($children, $flat);
					foreach($new_links as $link) {
						$links[] = $link;
					}
				}
				else {
					$links[] = $this->make_sitemap($children, $flat);
				}
			}
		}
		return $links;
	}

	
	// render as xml values
	public function render() {
		$url = engine_get('url');
		$xml_output = "<?xml version='1.0' encoding='UTF-8'?>\n";

		$xml_output .= "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"\n";
		$xml_output .= "\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
		$xml_output .= "\txsi:schemaLocation=\"http://www.sitemaps.org/schemas/sitemap/0.9\n";
		$xml_output .= "\t\thttp://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd\">\n";
		foreach($this->sitemap as $link) {
			if ($link['status'] == 1) {
				$xml_output .= "\t<url>\n";
				$xml_output .= "\t\t<loc>" . $url . "/" . $link['url'] . "</loc>\n";
				$xml_output .= "\t\t<changefreq>daily</changefreq>\n";
				$xml_output .= "\t\t<priority>" . round(($this->levels - $link['level']) / $this->levels, 1) . "</priority>\n";
				$xml_output .= "\t</url>\n";
			}
		}
		$xml_output .= "</urlset>";
	
		echo $xml_output;
	
	}
}

//"SELECT name, id, parent, status FROM pages WHERE status>0 ORDER BY hierarchy", true));
$smap = new SITEMAP($DB->filter("page", "active > 0 ORDER BY hierarchy"));

// show xml
header("Content-type: text/xml");
$smap->render();*/


?>